//
//  ChainNewsSearchVC.m
//  Chain
//
//  Created by zhaosh on 2018/4/4.
//  Copyright © 2018年 zhaosh. All rights reserved.
//
#import "ChainNewsSearchVC.h"
#import "ChainNewsInfo.h"
#import "ChainDBManager.h"
#import "ChainSearchView.h"
#import "ChainSearchHistoryFooterView.h"
#import "ChainNoDataView.h"
#import "ChainNewsCell.h"
#import "ChainSearchHistoryCell.h"
#import "JHSysAlertUtil.h"
#import "ChainSearchHistoryTagCell.h"
#import "MJRefreshBackStateFooter.h"

@interface ChainNewsSearchVC ()<ChainSearchViewDelegate,UITableViewDataSource,UITableViewDelegate,ChainSearchHistoryCelllDelegate,
ChainSearchHistoryFooterViewDelegate,UIGestureRecognizerDelegate>

@property(strong,nonatomic)NSMutableArray <ChainNewsInfo *> *infoList;
@property(strong,nonatomic)ChainSearchView *searchV;
@property(strong,nonatomic)NSMutableArray *dataArr;
@property(strong,nonatomic)NSMutableArray *historyDataArr;
@property(strong,nonatomic)UITableView *tableview;
@property(strong,nonatomic)NSString *searchKey;
@property(strong,nonatomic)UIView *tableHeaderView;
@property(assign,nonatomic)BOOL historyType;
@end

@implementation ChainNewsSearchVC{
    NSInteger pageNum;
}

-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}

-(NSMutableArray *)historyDataArr{
    if (!_historyDataArr) {
        _historyDataArr = [NSMutableArray new];
    }
    return _historyDataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    pageNum=1;
    
    self.historyType = YES;
    
    self.historyDataArr = [[[ChainDBManager shareClient] fetchNewsSearchHistory] mutableCopy];
    
    [self setHeadView];
    [self setupTableview];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:self.view.window];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.searchV.searchTextF becomeFirstResponder];
    });
}

-(void)tap:(UITapGestureRecognizer *)tap{
    [self.searchV endEditing:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.searchV endEditing:YES];
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    
    self.tableview.height = ScreenHeight - kTopHeight - keyboardRect.size.height;
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    self.tableview.height = ScreenHeight - kTopHeight;
}

- (void)setHeadView{
    self.fd_prefersNavigationBarHidden = YES;
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, kTopHeight)];
    headView.backgroundColor = HEXCOLOR(@"#ce0d0d");
    [self.view addSubview:headView];
    
    self.searchV = [[ChainSearchView alloc]initWithFrame:CGRectMake(30, kStatusBarHeight, ScreenWidth-7-44-30, 44)];
    self.searchV.delegate = self;
    self.searchV.searchViewType = FXSearchViewTypeTitleV;
    self.searchV.placeholder = @"请输入搜索关键词";
    [headView addSubview:self.searchV];
    
    UIButton *searchBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    searchBtn.frame = CGRectMake(self.searchV.right+2,kStatusBarHeight, 44, 44);
    [searchBtn setTitle:@"取消" forState:(UIControlStateNormal)];
    [searchBtn addTarget:self action:@selector(backAction) forControlEvents:(UIControlEventTouchUpInside)];
    searchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 7);
    searchBtn.titleLabel.font = FONT_LB(16.0);
    searchBtn.adjustsImageWhenHighlighted = NO;//取消点击时的高亮
    [headView addSubview:searchBtn];
}

-(void)setupTableview{
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, kTopHeight, ScreenWidth, ScreenHeight - kTopHeight) style:UITableViewStylePlain];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableview];
    
    self.tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 45)];
    [self.tableHeaderView setBackgroundColor:[UIColor whiteColor]];
    
    UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(15, 20, ScreenWidth-30, 15)];
    lbl.textColor = LableTextColor333;
    lbl.font = [UIFont systemFontOfSize:14];
    lbl.text=@"历史搜索";
    [self.tableHeaderView addSubview:lbl];
    
    UIButton *deleteBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame=CGRectMake(ScreenWidth-40, 20, 18, 17);
    [deleteBtn setBackgroundImage:[UIImage imageNamed:@"history_delete"] forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(footerVClearBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.tableHeaderView addSubview:deleteBtn];
    
    self.tableview.tableHeaderView =self.tableHeaderView;
    
    self.noDataView = [[ChainNoDataView alloc]initWithFrame:self.tableview.bounds];
    [self.tableview addSubview:self.noDataView];
    
    __weak typeof(self) weakself=self;
    //添加底部上提加载视图
    self.tableview.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
        if (!weakself.historyType) {
            weakself.tableview.mj_footer.hidden=NO;
            [weakself getNextData];
        }else{
            weakself.tableview.mj_footer.hidden=YES;
        }
    }];
    self.tableview.mj_footer.hidden=YES;
}

-(void)getNextData{
    pageNum++;
    self.historyType = NO;
    [self searchByName:self.searchKey andPageNum:[NSString stringWithFormat:@"%ld",pageNum]];
}

#pragma mark -- tableview delegate & datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.historyType) {
        if (self.historyDataArr.count==0) {
            return 0;
        } else {
            return 1;
        }
    }else{
        return self.dataArr.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.historyType) {
        ChainSearchHistoryTagCell *cell = [ChainSearchHistoryTagCell cellWithTableView:tableView];
        NSMutableArray * arr =[NSMutableArray arrayWithArray:[self getHistoryTitleName]];
        cell.array = arr;
        
        __weak typeof(self) weakself=self;
        [cell.tagListView setCompletionBlockWithSelected:^(NSInteger index) {
            ChainSearchHistoryItem *item  = [self.historyDataArr objectAtIndex:index];
            weakself.searchV.searchTextF.text=item.titlename;
            weakself.searchKey = item.titlename;
            [self.searchV endEditing:YES];
            weakself.historyType = NO;
            weakself.tableview.tableHeaderView = nil;
             self.tableview.mj_footer.hidden=NO;
            [weakself searchByName:item.titlename andPageNum:@"0"];
        }];
        return cell;
    }else{
        ChainNewsCell *cell = [ChainNewsCell cellWithTableView:tableView];
        cell.item = self.dataArr[indexPath.row];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.historyType) {
        NSMutableArray *nameArrayM=[NSMutableArray arrayWithArray:[self getHistoryTitleName]];
        return [ChainSearchHistoryTagCell getCellHeightWithItem:nameArrayM aView:[JCTagListView new] layout:[JCCollectionViewTagFlowLayout new]];
    }else{
        ChainNewsInfo *info = self.dataArr[indexPath.row];
        if (info.rowHeight) {
            return info.rowHeight;
        }else{
            ChainNewsCell *cell = [ChainNewsCell cellWithTableView:tableView];
            cell.item = info;
            [cell layoutSubviews];
            CGFloat rowH = cell.item.rowHeight;
            cell = nil;
            return rowH;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.searchV endEditing:YES];
    if (self.historyType) {
        self.historyType = !self.historyType;
        ChainSearchHistoryItem *item = self.historyDataArr[indexPath.row];
        self.searchV.searchTextF.text = item.titlename;
        self.searchV.searchTextF.rightViewMode = UITextFieldViewModeAlways;
        [self searchByName:item.titlename andPageNum:@"0"];
        [tableView reloadData];
    }else{
        //TO-DO 去往拜访详情页
        ChainNewsInfo *item = self.dataArr[indexPath.row];
    }
}


-(NSArray *)getHistoryTitleName{
    NSMutableArray *arrayM=[NSMutableArray array];
    for (int i=0; i<self.historyDataArr.count; i++) {
        ChainSearchHistoryItem *item = self.historyDataArr[i];
        [arrayM addObject:item.titlename];
    }
    return arrayM;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.searchV endEditing:YES];
}

#pragma mark -- searchF delegate methods
- (void)FXScheduleSearchVDelegateTextFieldShouldReturn:(NSString *)textFText{
    pageNum=1;
    self.historyType = NO;
    self.tableview.tableHeaderView = nil;
     self.tableview.mj_footer.hidden=NO;
    self.searchKey=textFText;
    [self searchByName:textFText andPageNum:[NSString stringWithFormat:@"%ld",pageNum]];
}

-(void)FXScheduleSearchVCleared{
    self.historyType = YES;
    self.historyDataArr = [[[ChainDBManager shareClient]fetchNewsSearchHistory] mutableCopy];
    self.noDataView.hidden = YES;
    self.tableview.tableHeaderView = self.tableHeaderView;
     self.tableview.mj_footer.hidden=YES;
    [self.tableview reloadData];
}

- (void)FXScheduleSearchVDelegateRightBtnAction:(UITextField *)textF{
    textF.text = @"";
    textF.rightViewMode = UITextFieldViewModeNever;
    pageNum=1;
    self.historyType = YES;
    self.historyDataArr = [[[ChainDBManager shareClient]fetchNewsSearchHistory] mutableCopy];
    self.tableview.tableFooterView.hidden = NO;
    self.tableview.tableHeaderView = self.tableHeaderView;
     self.tableview.mj_footer.hidden=YES;
    self.noDataView.hidden = YES;
    [self.tableview reloadData];
}

-(void)saveSearchHistoryToDB:(NSString *)searchKey{
    // 删除之前的搜索记录，保留新的搜索记录
    NSMutableArray * arr = [NSMutableArray arrayWithArray:[[[ChainDBManager shareClient]fetchNewsSearchHistory] mutableCopy]];
    for (ChainSearchHistoryItem * item in arr) {
        if ([item.titlename isEqualToString:searchKey]) {
            [[ChainDBManager shareClient]deleteNewsSearchHistoryById:item.id_];
        }
    }
    [[ChainDBManager shareClient]saveNewsHistoryWithTitle:searchKey];
}

#pragma footerDelegate method
-(void)footerVClearBtnClicked{
    [JHSysAlertUtil presentAlertViewWithTitle:@"提示" message:@"确认清空历史搜索" cancelTitle:@"取消" defaultTitle:@"确定" distinct:NO cancel:^{
        
    } confirm:^{
        [[ChainDBManager shareClient]deleteAllNewsSearchHistory];
        [self.historyDataArr removeAllObjects];
        [self.tableview reloadData];
    }];
}

-(void)searchByName:(NSString *)name andPageNum:(NSString *)pageNum{
    if([name isBlankString]){
        return;
    }
    self.historyType = NO;
     self.tableview.tableHeaderView = nil;
     self.tableview.mj_footer.hidden=NO;
    
    if ([pageNum isEqualToString:@"0"]) {
        [self showLoading];
        [self saveSearchHistoryToDB:name];
    }
    NSString *requestPage =[NSString stringWithFormat:@"%@",pageNum];
    NSDictionary *params = @{@"pageNo":requestPage,@"pageSize":@"10",@"title":name};
    NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,@"/latoutiao/news/getNewsList"];
    [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:params withHeader:nil andBlock:^(id data, NSError *error) {
        [self hideHUDafterDelay:0];
        
        NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
        if (error) {
            NSString *message=[info objectForKey:@"message"];
            [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.5];
        }else{
            NSString *success=[NSString stringWithFormat:@"%@",[info objectForKey:@"success"]];
            if ([success isEqualToString:@"1"]) {
                NSArray *tempArray=[data valueForKeyPath:@"value.rows"];
                
                for (NSDictionary *dic in tempArray) {
                    ChainNewsListModel *info = [ChainNewsListModel yy_modelWithDictionary:dic];
                    [self.dataArr addObject:info];
                }
            }
        }
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        
        [self.tableview reloadData];
    }];
}

#pragma mark -- searchCell delegate methods
-(void)searchdeleteActionWithCell:(ChainSearchHistoryCell *)cell{
    NSIndexPath *indexP = [self.tableview indexPathForCell:cell];
    ChainSearchHistoryItem *item = self.historyDataArr[indexP.row];
    [[ChainDBManager shareClient]deleteNewsSearchHistoryById:item.id_];
    
    [self.historyDataArr removeObjectAtIndex:indexP.row];
    
    [self.tableview deleteRowsAtIndexPaths:@[indexP] withRowAnimation:UITableViewRowAnimationLeft];
    if (self.historyDataArr.count == 0) {
        self.tableview.tableFooterView = [UIView new];
    }
}

-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    for (UIView *cell in self.tableview.visibleCells) {
        if ([touch.view isDescendantOfView:cell]) {
            return NO;
        }
    }
    return YES;
}

-(void)setHistoryType:(BOOL)historyType{
    _historyType = historyType;
    if (!historyType) {
        self.tableview.tableFooterView = [UIView new];
    }else{
 
    }
    [self.tableview reloadData];
}

@end
